<template>
  <el-dialog
    :visible="visible"
    title="上传数据"
    width="600px"
    class="upload-dialog"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :modal-append-to-body="true"
    :append-to-body="true"
  >
    <!-- Step 1: 上传文件 -->
    <div v-if="currentStep === 1" class="upload-step">
      <div class="upload-header">
        <h3>选择文件</h3>
      </div>

      <div v-if="!uploadedFile && !uploading" class="upload-dragger">
        <el-upload
          ref="uploadRef"
          drag
          action=""
          :http-request="() => {}"
          :before-upload="handleFileUpload"
          :show-file-list="false"
          accept=".zip"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传.zip文件</div>
        </el-upload>
      </div>

      <div v-if="uploading" class="upload-loading">
        <i class="el-icon-loading"></i>
        <p>正在处理文件...</p>
      </div>

      <div v-if="uploadedFile && !uploading" class="uploaded-file">
        <div class="file-info">
          <i class="el-icon-document"></i>
          <span>{{ uploadedFile.name }}</span>
          <!-- 二次确认 -->
          <el-popconfirm title="确定删除吗？" @confirm="removeFile">
            <el-button type="text" slot="reference">删除</el-button>
          </el-popconfirm>
        </div>
      </div>
    </div>

    <!-- Step 2: 选择图层 -->
    <div v-if="currentStep === 2" class="layer-selection-step">
      <div class="layer-selection-header">
        <h3>选择图层</h3>
        <p>请选择要导入的图层数据</p>
      </div>

      <div class="layer-selection">
        <el-select
          v-model="selectedLayer"
          placeholder="请选择图层"
          @change="handleLayerChange"
          style="width: 100%"
          clearable
        >
          <el-option
            v-for="layer in layerList"
            :key="layer.layerName"
            :label="layer.layerName"
            :value="layer.layerName"
          />
        </el-select>
      </div>

      <div class="layer-actions">
        <el-button @click="goBack">返回</el-button>
        <el-button
          type="primary"
          @click="goToMapping"
          :disabled="!selectedLayer"
        >
          下一步
        </el-button>
      </div>
    </div>

    <!-- Step 3: 字段映射 -->
    <div v-if="currentStep === 3" class="mapping-step">
      <div class="mapping-header">
        <h3>字段映射</h3>
        <p>请将模板字段与您的数据字段进行映射</p>
      </div>

      <div class="field-mapping">
        <h4>字段映射配置</h4>
        <div class="mapping-list">
          <div
            v-for="field in templateFields"
            :key="field.pkid"
            class="mapping-item"
          >
            <div class="mapping-label">
              <span>{{ field.problemContent }}</span>
              <span class="required-mark" v-if="field.requireStatus === '1'"
                >*</span
              >
            </div>
            <div class="mapping-select">
              <el-select
                v-model="fieldMapping[field.pkid]"
                placeholder="请选择对应字段"
                clearable
                style="width: 100%"
                size="small"
              >
                <el-option
                  v-for="dataField in selectedLayerFields"
                  :key="dataField"
                  :label="dataField"
                  :value="dataField"
                />
              </el-select>
            </div>
          </div>
        </div>
      </div>

      <div class="mapping-actions">
        <el-button @click="goBackToLayerSelection">返回</el-button>
        <el-button type="primary" @click="confirmMapping" :loading="importing">
          确认
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import {
  uploadFile,
  getGdbProperty,
  queryQuestionById,
  uploadGdb,
  deleteFile,
  uploadGdbSq
} from '@/api/question'
export default {
  name: 'UploadDialog',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    templateId: {
      type: String,
      default: '',
    },
    isExtraTip: {
      type: Boolean,
      default: false,
    },
    type: {
      type: String,
      default: '',
    }
  },
  data() {
    return {
      currentStep: 1,
      uploadedFile: null,
      uploading: false,
      importing: false,
      uploadId: null,
      layerList: [],
      selectedLayer: '',
      selectedLayerFields: [],
      templateFields: [],
      fieldMapping: {},
      uploadType: ''
    }
  },
  watch: {
    type: {
      handler(newVal) {
        this.uploadType = newVal
      },
    },
  },
  methods: {
    handleClose() {
      this.$emit('close')
      this.resetDialog()
    },

    resetDialog() {
      this.currentStep = 1
      this.uploadedFile = null
      this.uploading = false
      this.importing = false
      this.uploadId = null
      this.layerList = []
      this.selectedLayer = ''
      this.selectedLayerFields = []
      this.templateFields = []
      this.fieldMapping = {}
    },
    async handleUpload(file) {
      const allowedTypes = ['application/zip', 'application/x-zip-compressed']

      if (!allowedTypes.includes(file.type)) {
        this.$message.error('只支持.zip文件！')
        return false
      }

      this.uploadedFile = file
      this.uploading = true

      try {
        const formData = new FormData()
        formData.append('file', file)
        formData.append('type', 'gdb')

        const uploadResponse =  await uploadFile(formData)

        if (uploadResponse && uploadResponse.data) {
          this.uploadId = uploadResponse.data

          const propertyResponse = await getGdbProperty({
            fileId: this.uploadId,
          })

          if (propertyResponse && propertyResponse.data) {
            this.layerList = propertyResponse.data

            if (this.layerList.length === 0) {
              this.$message.error('文件中没有有效图层数据！')
              return false
            }

            this.currentStep = 2
            this.$message.success('文件处理成功！请选择要导入的图层')
          } else {
            this.$message.error('获取图层数据失败！')
            return false
          }
        } else {
          this.$message.error('文件上传失败！')
          return false
        }
      } catch (error) {
        console.error('Upload error:', error)
        this.$message.error('文件处理失败，请重试！')
        return false
      } finally {
        this.uploading = false
      }

      return false
    },

     handleFileUpload(file) {
      if (this.isExtraTip) {
        this.$confirm('上传数据会覆盖现有数据(图片会丢失),是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then((res) => {
          if (res) {
            this.handleUpload(file)
          }
        })
        return
      }else{
        this.handleUpload(file)
      }
    },

    removeFile() {
      deleteFile({
        resourceId: this.uploadId,
      }).then((res) => {
        if (res && res.success) {
          this.$message.success('文件删除成功！')
          this.uploadedFile = null
          this.uploadId = null
          this.selectedLayer = ''
          this.selectedLayerFields = []
          this.templateFields = []
          this.fieldMapping = {}
          this.currentStep = 1
        } else {
          this.$message.error(res.message)
        }
      })
    },

    async handleLayerChange(layerName) {
      if (!layerName) {
        this.selectedLayerFields = []
        return
      }

      const selectedLayerData = this.layerList.find(
        (layer) => layer.layerName === layerName
      )
      if (selectedLayerData) {
        this.selectedLayerFields = selectedLayerData.fields || []
      }

      try {
        const templateResponse = await queryQuestionById({
          templateId: this.templateId,
        })
        if (templateResponse && templateResponse.data) {
          // 过滤problemType 4,8,10,12,24,26,28,29
          const filteredProblems = templateResponse.data.problems.filter(
            (item) =>
              !['4', '8', '10', '12', '24', '26', '28', '29'].includes(
                item.problemType
              )
          )
          // 平铺children字段
          this.templateFields = this.flattenFields(filteredProblems)
          // 设置默认映射
          this.setDefaultMapping()
        } else {
          this.$message.error('获取模板字段失败！')
        }
      } catch (error) {
        console.error('Template error:', error)
        this.$message.error('获取模板字段失败，请重试！')
      }
    },

    // 平铺字段（包含children）
    flattenFields(fields) {
      const result = []

      const flatten = (fieldList) => {
        fieldList.forEach((field) => {
          // 过滤problemType 4,8,10,12,24,26,28,29
          if (
            ['4', '8', '10', '12', '24', '26', '28', '29'].includes(
              field.problemType
            )
          ) {
            return
          }
          result.push(field)

          // 如果有children，递归处理
          if (field.children && field.children.length > 0) {
            flatten(field.children)
          }
        })
      }

      flatten(fields)
      return result
    },

    // 设置默认映射（相同名称的字段自动选中）
    setDefaultMapping() {
      const newMapping = {}

      this.templateFields.forEach((templateField) => {
        const matchingDataField = this.selectedLayerFields.find(
          (dataField) => dataField === templateField.problemContent
        )

        if (matchingDataField) {
          newMapping[templateField.pkid] = matchingDataField
        }
      })

      this.fieldMapping = { ...this.fieldMapping, ...newMapping }
    },

    goBack() {
      this.currentStep = 1
    },

    goBackToLayerSelection() {
      this.currentStep = 2
    },

    goToMapping() {
      if (!this.selectedLayer) {
        this.$message.error('请先选择图层！')
        return
      }
      this.currentStep = 3
    },

    async confirmMapping() {
      const requiredFields = this.templateFields.filter(
        (field) => field.requireStatus === '1'
      )
      const missingFields = []

      for (const field of requiredFields) {
        if (!this.fieldMapping[field.pkid]) {
          missingFields.push(field.problemContent)
        }
      }

      if (missingFields.length > 0) {
        this.$message.error(`请配置必填字段：${missingFields.join(', ')}`)
        return
      }

      this.importing = true

      try {
        const mappingConfig = {
          layerName: this.selectedLayer,
          fileId: this.uploadId,
          questionMap: this.fieldMapping,
          templateId: this.templateId,
        }
        console.log('mappingConfig', mappingConfig)

        const res = this.uploadType === 'sq' ? await uploadGdbSq(mappingConfig) : await uploadGdb(mappingConfig)
        if (res && res.success) {
          this.$message.success('数据导入成功！')
          this.handleClose()
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.error('Import error:', error)
        this.$message.error('数据导入失败，请重试！')
      } finally {
        this.importing = false
      }
    },
  },
}
</script>

<style lang="scss" scoped>
:deep(.el-dialog__wrapper) {
  z-index: 9999 !important;
}

:deep(.el-dialog) {
  z-index: 10000 !important;
}

.upload-step {
  padding: 20px;

  .upload-header {
    text-align: center;
    margin-bottom: 24px;

    h3 {
      margin: 0 0 8px 0;
      color: #333;
    }

    p {
      margin: 0;
      color: #666;
      font-size: 14px;
    }
  }

  .upload-dragger {
    text-align: center;

    :deep(.el-upload) {
      display: inline-block;
      text-align: left;
    }

    :deep(.el-upload-dragger) {
      width: 400px;
      height: 180px;
      border: 2px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: border-color 0.3s;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      &:hover {
        border-color: #409eff;
      }

      .el-icon-upload {
        font-size: 67px;
        color: #c0c4cc;
        margin-bottom: 16px;
        line-height: 50px;
      }

      .el-upload__text {
        color: #606266;
        font-size: 14px;
        text-align: center;
        margin-bottom: 8px;

        em {
          color: #409eff;
          font-style: normal;
        }
      }
    }

    :deep(.el-upload__tip) {
      font-size: 12px;
      color: #606266;
      text-align: center;
      margin-top: 8px;
    }
  }

  .upload-loading {
    text-align: center;
    width: 400px;
    height: 180px;
    border: 2px dashed #d9d9d9;
    border-radius: 6px;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .el-icon-loading {
      font-size: 67px;
      color: #409eff;
      margin-bottom: 16px;
      line-height: 50px;
    }

    p {
      margin: 0;
      color: #606266;
      font-size: 14px;
    }
  }

  .uploaded-file {
    text-align: center;
    width: 400px;
    height: 180px;
    border: 2px solid #e4e7ed;
    border-radius: 6px;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: #f5f7fa;

    .file-info {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 12px;

      .el-icon-document {
        font-size: 67px;
        color: #409eff;
        line-height: 50px;
      }

      span {
        color: #333;
        font-size: 14px;
      }
    }
  }
}

.layer-selection-step {
  padding: 20px;

  .layer-selection-header {
    text-align: center;
    margin-bottom: 24px;

    h3 {
      margin: 0 0 8px 0;
      color: #333;
    }

    p {
      margin: 0;
      color: #666;
      font-size: 14px;
    }
  }

  .layer-selection {
    margin-bottom: 24px;
  }

  .layer-actions {
    display: flex;
    justify-content: center;
    gap: 12px;
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #e4e7ed;
  }
}

.mapping-step {
  padding: 20px;

  .mapping-header {
    text-align: center;
    margin-bottom: 24px;

    h3 {
      margin: 0 0 8px 0;
      color: #333;
    }

    p {
      margin: 0;
      color: #666;
      font-size: 14px;
    }
  }

  .template-preview,
  .data-preview {
    margin-bottom: 24px;

    h4 {
      margin: 0 0 12px 0;
      color: #333;
      font-size: 14px;
    }
  }

  .template-fields,
  .data-fields {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 12px;
    background: #f8f9fa;

    .template-field,
    .data-field {
      display: flex;
      align-items: center;
      padding: 4px 0;
      font-size: 13px;

      .field-name {
        color: #333;
      }

      .field-required {
        color: #f56c6c;
        margin-left: 4px;
      }
    }
  }

  .field-mapping {
    h4 {
      margin: 0 0 16px 0;
      color: #333;
      font-size: 14px;
    }

    .mapping-list {
      .mapping-item {
        display: flex;
        align-items: center;
        gap: 16px;
        padding: 8px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .mapping-label {
          width: 120px;
          font-size: 13px;
          color: #333;

          .required-mark {
            color: #f56c6c;
            margin-left: 4px;
          }
        }

        .mapping-select {
          flex: 1;
          //   max-width: 300px;
        }
      }
    }
  }

  .mapping-actions {
    display: flex;
    justify-content: center;
    gap: 12px;
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #e4e7ed;
  }
}
</style>
